<?php
class CmsCurrencyModel extends ModelArray
{
	protected static $instance;

	public static function GetInstance()
	{
        return self::$instance ? self::$instance : self::$instance = new CmsCurrencyModel();
	}

    protected function LoadFields()
    {
        $this->AddField('id', 'varchar', false, true);
        $this->AddField('name');
        $this->AddField('symbol');
        $this->AddField('isrightsymbol', 'bool');
        $this->AddField('rate', 'number');
    }

	public static function GetDefault()
	{
		return self::GetInstance()->FindById(AppConfig::GetInstance()->DEFAULT_CURRENCY);
	}

    public static function Convert($price, $rate)
    {
        return $price * $rate;
    }

	public static function FormatPrice($price, $id = null, $rate = null)
	{
        if (!$id) $id = AppConfig::GetInstance()->GetCurrencyId();
        $currency = self::GetInstance()->FindById($id);
        $rate = is_null($rate) ? $currency['rate'] : $rate;
        $price = self::Convert($price, $rate);
        return self::FormatSign(self::Format($price), $currency);
	}

	public static function Format($value)
	{
        return number_format($value, AppConfig::GetInstance()->CURRENCY_NUMBER_OF_DECIMALS, '.', ',');
	}

    public static function FormatDefaultPrice($price)
    {
        $currency = CmsCurrencyModel::GetDefault();
        $price = self::Format($price);
        return self::FormatSign($price, $currency);
    }

    protected static function FormatSign($price, $currency)
    {
        $minus = null;
        if ($price<0)
        {
            $price = 0-$price;
            $minus = '-';
        }
        return $minus.($currency['isrightsymbol'] ? $price.$currency['symbol'] : $currency['symbol'].$price);
    }
}
?>
